﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using EFCore.AspNet.Sample.Data;
using EFCore.AspNet.Sample.Models;
using Microsoft.EntityFrameworkCore;
using System.Threading;

namespace EFCore.AspNet.Sample.Pages.Courses
{
    public class CreateModel : DepartmentNamePageModel
    {
        private readonly EFCore.AspNet.Sample.Data.SchoolContext _context;

        public CreateModel(EFCore.AspNet.Sample.Data.SchoolContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> OnGet()
        {
            PopulateDepartmentsDropDownList(_context);

            var t = DoworkAsync();

            return await Task.FromResult(Page());

            //return Page();
        }

        protected async Task DoworkAsync()
        {
            int userId = await Task.Run(() =>
            {
                //★重点在此处
                System.Threading.Thread.Sleep(6100);
                //真正代码
                return 55;
            });

            //阻塞之后继续执行的代码 <-- 不是阻塞，用挂起可能更合适
            await GetUserAsync(userId);
        }

        public async Task<Course> GetUserAsync(int id)
        {
            return await _context.Courses.FirstOrDefaultAsync();
        }


        [BindProperty]
        public Course Course { get; set; }

        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            var emptyCourse = new Course();

            if (await TryUpdateModelAsync<Course>(
                 emptyCourse,
                 "course",   // Prefix for form value.
                 s => s.CourseID, s => s.DepartmentID, s => s.Title, s => s.Credits))
            {
                _context.Courses.Add(emptyCourse);
                await _context.SaveChangesAsync();
                return RedirectToPage("./Index");
            }

            // Select DepartmentID if TryUpdateModelAsync fails.
            PopulateDepartmentsDropDownList(_context, emptyCourse.DepartmentID);
            return Page();
        }
    }
}
